//
//  WWRequestAPI.m
//  WangLottery
//
//  Created by 黄修勇 on 12-9-10.
//
//

#import "WWRequestAPI.h"
#import "WWDataParser.h"

@implementation WWRequestAPI


static WWRequestAPI * api=nil;

+(WWRequestAPI *)currentRequestAPI{

    @synchronized(self){
    
        if (!api) {
            api=[[super allocWithZone:NULL]init];
        }
    }
    return api;
}

-(id)init{

    self=[super init];
    if (self) {
        requestService=[[WWRequestService alloc]init];
        requestArray=[NSMutableArray new];
        parser=[[WWDataParser alloc]init];
    }
    return self;
}


-(void)dealloc{

    for (WWRequest *request in requestArray) {
        [request.request clearDelegatesAndCancel];
    }
    [requestArray removeAllObjects];
    [requestArray release];
    [requestService release];
    [parser release];
    [super dealloc];
}


-(long)requestWithAction:(NSString *)action paras:(NSDictionary *)dic target:(id)target parserSEL:(SEL)sel{

    NSError *error=nil;
        
    NSString *host=[NSString stringWithFormat:@"%@%@",kRequestURL,action];
    
    ASIFormDataRequest *request=[requestService postFormRequestWithURL:host params:dic target:self timeOut:kTimeOut error:&error];
    if (!request) {
        NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"0",@"result",[error localizedDescription],@"reason", nil];
        if (target&&[target respondsToSelector:@selector(requesResult:)]) {
            [target requesResult:dic];
        }
        return -1;
    }
    WWRequest *tempRequest=[[WWRequest alloc]init];
    tempRequest.request=request;
    tempRequest.tag=requestTag;
    tempRequest.parserSEL=sel;
    requestTag++;
    tempRequest.target=target;
    tempRequest.action=action;
    [requestArray addObject:tempRequest];
    [tempRequest release];
    return tempRequest.tag;
}

-(BOOL)cancelRequestWithTag:(long)tag{

    for (WWRequest *request in requestArray) {
        if (request.tag==tag) {
            [request.request clearDelegatesAndCancel];
            [requestArray removeObject:request];
            return YES;
        }
    }
    return NO;
}

#pragma mark -ASIHTTPRequestDelegate

-(void)requestFailed:(ASIHTTPRequest *)request{

    NSError *error=[request error];
    NSString *errorString=[error localizedDescription];
    NSString *chineseError=nil;
    if ([errorString isEqualToString:@"The request timed out"]) {
        chineseError=@"请求超时";
    }else if ([errorString isEqualToString:@"The request was cancelled"]){
        chineseError=@"用户取消请求";
    }else if ([errorString isEqualToString:@"Unable to create request (bad url?)"]){
        chineseError=@"请求创建失败";
    }else{
        chineseError=@"请求失败";
    }
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"result",chineseError,@"reason", nil];
    for (WWRequest *wRequest in requestArray) {
        if ([wRequest.request isEqual:request]) {
            if (wRequest.target&&[wRequest.target respondsToSelector:@selector(requesResult:)]) {
                [wRequest.target requesResult:dic];
                [requestArray removeObject:wRequest];
                break;
            }
        }
    }
}

-(void)requestFinished:(ASIHTTPRequest *)request{

    CLog(@"request string %@",request.responseString);
    
    for (WWRequest *wRequest in requestArray) {
        if ([wRequest.request isEqual:request]) {
            if (wRequest.target&&[wRequest.target respondsToSelector:@selector(requesResult:)]) {
                NSDictionary *resultDic=nil;
                if (wRequest.parserSEL) {
                    resultDic=[parser performSelector:wRequest.parserSEL withObject:request.responseString];
                }
        
                [wRequest.target requesResult:resultDic];
                [requestArray removeObject:wRequest];
                break;
            }
        }
    }
}


#pragma mark - Sigle


+ (id)allocWithZone:(NSZone *)zone
{
    return [[self currentRequestAPI] retain];
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;
}

- (id)autorelease
{
    return self;
}

-(oneway void)release{
    
}

@end


@implementation WWRequest

@synthesize tag=_tag;
@synthesize request=_request;
@synthesize target=_target;
@synthesize action=_action;
@synthesize parserSEL=_parserSEL;

-(id)init{

    self=[super init];
    if (self) {
        _tag=-1;
        _request=nil;
        _target=nil;
        _parserSEL=nil;
        self.action=nil;
    }
    return self;
}

-(void)dealloc{

    _request=nil;
    _target=nil;
    _parserSEL=nil;
    [_action release];
    [super dealloc];
}

@end